//获取应用实例
const app = getApp();
const common = require("../../../utils/common.js");
import { $wuxToast } from "../../../miniprogram_npm/weapp/index.js";

import {add, multiply} from "../../../utils/util.js";
Page({
  data: {
    lock:false,
    id: 0,
    isCopy: false,// 当前是否拷贝模式
    current: "tab1",
    confOrderType: [],

    bomTypes: [
        {
            label:"面料",
            value:"面料"
        },
        {
            label:"辅料",
            value:"辅料"
        },
        {
            label:"配料",
            value:"配料"
        },
        {
            label:"包装辅料",
            value:"包装辅料"
        },
        {
            label:"二次工艺",
            value:"二次工艺"
        },
        {
            label:"加工费",
            value:"加工费"
        },
    ],
    //阿尔法表单数据
    alphaFormData: {
        isBuildMake: 1,
        isBuildProduct: 1,
      bomList: [],
      id: "",
    },
    /***********************************阿尔法*******************************/
  },

  /********************************************************阿尔法***************************************************************/
  computedMakePrice(){
    var alphaFormData = this.data.alphaFormData
    var totalPrice = alphaFormData.bomList.reduce((acc, val)=>{
        var aa = add(acc,multiply(val.price,val.singleUsage));
        return aa
    },0);
    alphaFormData.makePrice = totalPrice
    this.setData({
        alphaFormData
    })
  },
  errmsg(msg = "") {
    $wuxToast().show({
      type: "cancel",
      duration: 1000,
      color: "#fff",
      text: msg,
      success: () => console.log("拦截提示"),
    });
  },

  //获取详情后，设置对应索引值 以 展示数据
  setMetaDataIndex() {
    let alphaFormData = this.data.alphaFormData;
    let applyTypeIndex = this.data.confOrderType.findIndex(
      (v) => alphaFormData.applyType == v.value
    );
    alphaFormData.applyTypeIndex = applyTypeIndex == -1 ? "" : applyTypeIndex;
    this.data.alphaFormData.bomList.forEach((v,k)=>{
        let bomTypeIndex = this.data.bomTypes.findIndex(
            (v2) => v.bomType == v2.value
          );
        v.bomTypeIndex = bomTypeIndex
    })
    this.setData({
      alphaFormData,
    });
  },

  // 预览图片
  PreviewImg: function (events) {
    var pic_arr = events.currentTarget.dataset.pic;
    // 调用
    wx.previewImage({
        current: pic_arr[0], // 当前显示图片的http链接
        urls: pic_arr // 需要预览的图片http链接列表
    })
},
  //设置基础信息
  setAlphaFormData() {
    let alphaFormData = this.data.alphaFormData
    alphaFormData.bomList.forEach((v,k)=>{
        v.bomType = this.data.bomTypes[v.bomTypeIndex].value
    })
    if(this.data.isCopy == true ){
        alphaFormData.id = null;
    }
    this.setData({
        alphaFormData,
    })
    this.submitForm();
  },

  //提交表单
  submitForm() {
    let data = this.data.alphaFormData;
    common
      .request_api(
        (this.data.id > 0 && this.data.isCopy == false) ? "/api/erp/other/makeApplyOrder/updateOrder" : "/api/erp/other/makeApplyOrder/createOrder",
        { ...data },
        true,
        "post"
      )
      .then((res) => {
        if (res.code == 200) {
          wx.showToast({
            title: res.msg,
            icon: "success",
            duration: 1500,
          });
          // wx.navigateTo({
          //   url: "/alpha/pages/alpha_material/index",
          // });
          wx.navigateBack({
            delta: 1
          })
        }
      });
  },
  getConfOrderType() {
    common
      .request_api(
        "/api/erp/baseDictionary/queryCommonDictionaryAndChild/confOrderCategory?code=1003",
        {},
        true,
        "get"
      )
      .then((res) => {
        this.setData({
            confOrderType: res.data,
        });

        this.getList();
      });
  },


  compuctSetDataIndex(e) {
    this.setDataIndex(e);
    let { index, index2 } = e.currentTarget.dataset;
    this.compuctPrice(index, index2);
  },

  //删除sku行
  delSku(e) {
    let { index2 } = e.currentTarget.dataset;
    let list = this.data.alphaFormData.bomList;
    list.splice(index2, 1);
    this.setData({
      ["alphaFormData.bomList"]: list,
    });
    this.computedMakePrice()
  },

  //sku增加行
  addSku(e) {
    let list = this.data.alphaFormData.bomList;
    list.push({
      bomTypeIndex: 0,
    });
    this.setData({
      ["alphaFormData.bomList"]: list,
    });
  },

  // // 重置
  // resetDto(){

  // },


  //sku采购价编辑，同时写入基础价格
  skuPriceComputedChange(e) {
    this.setDataIndex(e);
  },


  //变更设置
  setDataIndex: function (e) {
    let { field } = e.currentTarget.dataset;
    let value = e.detail.value

    //判断指定字段值只能是【数值类型】
    let field_arr = field.split(".");
    let last_field = field_arr[field_arr.length-1]||''
    if(["productQty","productPrice","makeQty","sort","price","singleUsage"].includes(last_field)){
        value = value.replace(/[^0-9.]/g, ''); // 只允许数字和小数点
    }


    this.setData({
      [field]: value,
    });

    if(["singleUsage","price"].includes(last_field)){
        this.computedMakePrice();
    }
  },
  setDataIndex2: function (e) {
    let value = e.detail.value
    const obj = this.data.outsourceTypeList[value]
    this.setData({
      'alphaFormData.outsourceTypeIndex': value,
    });
  },
  
  //资料页面切换
  navChange(e) {
    this.setData({
      current: e.detail.key,
    });
  },

  //获取数据详情
  getMaterialDetail() {
    common
      .request_api(
        "/api/erp/other/makeApplyOrder/getDetail",
        {
          id: this.data.id ,
        },
        true,
        "post"
      )
      .then((res) => {
        this.setData({
          alphaFormData: res.data,
        });
        this.setMetaDataIndex();
      });
  },

  /**************************************************************阿尔法*******************************************************/

  onShow() {
      

    this.getConfOrderType();
   
  },
  onLoad: function (options) {

    // 设置标题
    wx.setNavigationBarTitle({
      title: "新建加工申请",
    });

    // 如果是编辑的话
    if (options.id != undefined && options.id > 0) {
      // 重设标题
      wx.setNavigationBarTitle({
        title: "编辑加工申请",
      });
      this.setData({
        id: options.id,
      });
    }

    if (options.isCopy != undefined && options.isCopy == 1) {
        wx.setNavigationBarTitle({
            title: "新建加工申请",
          });
        this.setData({
            isCopy: true,
          });
    }

    //生成年份
    common.generateYearArray((yearArray, defaultIndex) => {
      console.log("yearArray,defaultIndex", yearArray, defaultIndex);
      this.setData({
        yearArray: yearArray,
        defaultYearIndex: defaultIndex,
      });
    });
    
  },

  getList(){
    if(this.data.lock===true){
      return;
    }
    if (this.data.id > 0) {
      this.getMaterialDetail();
    }
  },

  // 预览图片
  PreViewImg: function (events) {
    var __this = this;
    // 数据下标
    var index = events.currentTarget.dataset.index;
    var path = events.currentTarget.dataset.path;
    var file_arr = [];
    // 取出所有图片的链接
    for (var i = 0; i < __this.data.tempFiles.length; i++) {
      file_arr.push(__this.data.tempFiles[i].tempFilePath);
    }
    // 调用
    wx.previewImage({
      current: path, // 当前显示图片的http链接
      urls: file_arr, // 需要预览的图片http链接列表
    });
  },
  getValueFromPath(obj, path) {
    const keys = path.replace(/\[(\d+)\]/g, '.$1').split('.');
    return keys.reduce((acc, key) => acc && acc[key], obj);
  },
});
